/**
 * Historico de alteração
 *
 * Data         Autor   Descrição
 * 24/10/2010   Jerry   Criação do cabeçalho.
 *
 */

package Dados;

/**
 *
 * @author Bruno
 */
public class Fila {
    
    private class No {
        
        private Pacote data;
        private No prev;
        private No next;
        
        public No(Pacote data, No prev, No next) {
            this.data = data;
            this.prev = prev;
            this.next = next;
        }
        
        public Pacote getData() {
            return data;
        }
        
        public No getNext() {
            return next;
        }
        
        public No getPrev() {
            return prev;
        }
        
        public void setNext(No next) {
            this.next = next;
        }
        
        public void setPrev(No prev) {
            this.prev = prev;
        }
        
    }
    
    private No begin;
    private No end;
    private int length;
    
    public Fila() {
        begin = null;
        end = null;
        length = 0;
    }
    
    public synchronized void insert(Pacote data) {
        
        if(length == 0)
            notify();
        
        No aux = begin;
        
        begin = new No(data, null, begin);
        
        if(aux != null)
            aux.setPrev(begin);
        
        if(end == null)
            end = begin;
        
        length++;
        
    }
    
    public synchronized Pacote remove() {
        
        Pacote b = null;
        
        try {
            if(length == 0)
                wait();
            
            b = end.getData();
            end = end.getPrev();
            
            if(end == null)
                begin = null;
            else
                end.setNext(null);
            
            length--;
        }
        catch(InterruptedException ex) {
            ex.printStackTrace();
        }
        finally {
            return b;
        }
        
    }
    
    public int getLength() {
        return length;
    }
    
}

